﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Config
{
    /// <summary>
    /// 读取或写入ConfigObjects内类
    /// </summary>
    public class ConfigUtil
    {
        private static readonly string temp_suffix = ".temp";
        private static readonly string complete_suffix = ".complete";

        /// <summary>
        /// 读配置
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="temp_fix">自动读取临时文件</param>
        /// <returns>读取状态</returns>
        public static T Read<T>(string path, bool temp_fix = true)
        {
            try
            {
                var temp_path = path + temp_suffix;
                var complete_path = path + complete_suffix;
                if (File.Exists(temp_path) && File.Exists(complete_path) && temp_fix)
                {
                    File.Copy(temp_path, path, true);//临时文件内容复制到原保存文件
                    File.Delete(complete_path);//完毕后删除临时文件
                    File.Delete(temp_path);//完毕后删除临时文件
                }
                using (var jsonTextReader = new JsonTextReader(File.OpenText(path)))
                {
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<T>(jsonTextReader);
                }
            }
            catch (System.Exception)
            {
                //Console.WriteLine(ex.ToString());
                throw;
            }
        }
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="config">配置</param>
        /// <returns></returns>
        public static bool Write<T>(string path, T config)
        {
            try
            {
                var temp_path = path + temp_suffix;
                var complete_path = path + complete_suffix;
                var serializer = new JsonSerializer() { Formatting = Formatting.Indented };
                using (var sw = new StreamWriter(File.Open(temp_path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)))
                {
                    serializer.Serialize(sw, config);
                    sw.Flush();
                }
                using (var f = File.Create(complete_path))
                {
                    File.Copy(temp_path, path, true);//临时文件内容复制到原保存文件
                }
                File.Delete(complete_path);//完毕后删除临时文件
                File.Delete(temp_path);//完毕后删除临时文件

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
    }
}
